import classes from './index.module.less';

import { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { nanoid } from 'nanoid';
import { Tabs, TabsProps } from 'antd';
import { Editor } from '@lle/d3-editor';

import { useSize } from '@/hooks/useSize';
import { IPart, IRack } from '@/types';
import { fetchLayout } from '@/api/layout';

import { PartList, RackList, SceneList, SideBar, ToolBar } from './components';
import { message } from '@/App';

// 240923-03-0002-0001 zxjj
// 240924-01-0006-0001 zdy
const Home = () => {
  const [params] = useSearchParams();
  const container = useRef<HTMLDivElement>(null!);
  const size = useSize(container);
  const [editor, setEditor] = useState<Editor>();
  const [plHangNo, setPlHangNo] = useState<string>();

  useEffect(() => {
    const plHangNo = params.get('plHangNo');
    if (plHangNo) {
      setPlHangNo(plHangNo);
    }
  }, [params]);

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '零件任务库',
      children: <PartList plHangNo={plHangNo} editor={editor} />,
    },
    {
      key: '2',
      label: '挂具库',
      children: <RackList />,
    },
    {
      key: '3',
      label: '场景',
      children: <SceneList editor={editor} />,
    },
  ];

  useEffect(() => {
    if (!plHangNo) return;

    const editor = new Editor();

    editor.mount(container.current);

    const getData = async (plHangNo: string) => {
      const response = await fetchLayout(plHangNo);

      editor.open(response.data);
    };

    getData(plHangNo);

    setEditor(editor);
    return () => {
      editor.unmount();

      setEditor(undefined);
    };
  }, [plHangNo]);

  useEffect(() => {
    editor?.resize();
  }, [editor, size]);

  const onDropItem = async (e: React.DragEvent) => {
    e.preventDefault();
    const transferData = e.dataTransfer.getData('text');

    const data = JSON.parse(transferData) as { type: string; item: unknown };

    if (data.type === 'part') {
      const item = data.item as IPart;
      if (item.applyNum === 0) {
        message.info('待排数量为0');
        return;
      }
      editor?.partsManager.dropPart(item, e.nativeEvent);
    } else {
      const item = data.item as IRack;
      const model = {
        ...item,
        id: nanoid(),
        position: { x: 0, y: 0, z: 0 },
      };

      editor?.layoutManagere.dropRack(model, e.nativeEvent);
    }
  };

  return (
    <div className={classes.container}>
      <div className={classes.left}>
        <Tabs defaultActiveKey="1" items={items} />
      </div>
      <div
        className={classes.right}
        ref={container}
        onDrop={onDropItem}
        onDragOver={e => e.preventDefault()}
      >
        {editor && plHangNo && <ToolBar editor={editor} plHangNo={plHangNo} />}
        {editor && <SideBar editor={editor} />}
      </div>
    </div>
  );
};

export default Home;
